import React, {Component} from 'react';
import cn from 'classnames';
import _ from 'underscore';
import $ from 'jquery';
import {} from 'jquery.cookie';
import moment from 'moment';

import dispatcher from 'lib/dispatcher';

class SegmentDateStore {
  constructor() {
    this.$state = {
      text:'今日',
      isOpen:false,
      dateListSelectedValue:'TODAY',
      dateList:[
        {
          id:1,
          value:'TODAY',
          text:'今日'
        },{
          id:2,
          value:'YESTERDAY',
          text:'昨天'
        },{
          id:3,
          value:'THREE',
          text:'3天'
        },{
          id:7,
          value:'SEVEN',
          text:'7天'
        },{
          id:15,
          value:'FIFTEEN',
          text:'15天'
        },
        // {
        //   id:30,
        //   value:'THIRTY',
        //   text:'30天'
        // }
      ]
    };

    this.getState = this.getState.bind(this);
    this._handle = this._handle.bind(this);
    this.dispose = this.dispose.bind(this);
    this.getValue = this.getValue.bind(this);

    if(BlueWare.userStatus==='FREE'||BlueWare.userStatus==='PAIED'){
      this.$state.dateList = _.filter(this.$state.dateList, i=>i.id <= 7);
    }

    let [spanInCookie, endInCookie] = [$.cookie('spanTime',Number), $.cookie('endTime',Number)];
    if ((!endInCookie || isNaN(endInCookie)) && !!spanInCookie) {
      let duration = parseInt(moment.duration(spanInCookie).asDays());
      if (duration) {
        let item = _.find(this.$state.dateList, i=>i.id === duration);
        if (item) {
          _.extend(this.$state, {
            dateListSelectedValue:item.value,
            text:item.text
          });
        }
      }
    }
  }

  getValue() {
    return this.$state.dateListSelectedValue;
  }

  _handle(payload) {
    var payLoadName = payload.$type.toLowerCase()
    if(this['$' + payLoadName]) {
      this['$' + payLoadName](payload)
    }
  }

  dispose() {
    if (this._handleToken) {
      dispatcher.unregister(this._handleToken);
    }
  }

  getState(viewInstance) {
    this.emit = (callback) => {
      if (callback) {
        viewInstance.setState(this.$state, callback);
      } else {
        viewInstance.setState(this.$state);
      }
    };
    this._handleToken = dispatcher.register(this._handle);

    return this.$state;
  }

  $segment_date_picker_toggle() {
    this.$state.isOpen = !this.$state.isOpen;

    this.emit();
  }

  $set_segment_date(payload) {
    _.extend(this.$state,{
      dateListSelectedValue:payload.item.value,
      isOpen:false,
      text:payload.item.text
    });

    let option = {path:'/'};
    if (document.domain.indexOf(BlueWare.siteDomain)>-1){
      option.domain = BlueWare.siteDomain;
    }
    $.cookie('spanTime',moment.duration(payload.item.id, 'days').valueOf(),option);
    $.cookie('endTime',null,option);

    this.emit(()=>{
      dispatcher.dispatch({
        $type:'SETTIME',
        data:{
          spanTime:moment.duration(payload.item.id, 'days').valueOf(),
          endTime:null
        }
      });

      this.emit();
    });
  }
}

export default class SegmentDatePicker extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = props.scope.getState(this);

    this.closeMenu = this.closeMenu.bind(this);
  }

  toggleHandler() {
    dispatcher.dispatch({
      $type:'segment_date_picker_toggle'
    });
  }

  selectItem(item){
    dispatcher.dispatch({
      $type:'set_segment_date',
      item
    });
  }

  closeMenu(e){
    if (this.state.isOpen) {
      let el = e.target
        , container = this.refs.root;
      if (!$.contains(container,el)){
        this.setState({isOpen:false});
      }
    }
  }

  componentDidMount() {
    $('body').on('click',this.closeMenu);
  }

  componentWillUnmount() {
    $('body').off('click',this.closeMenu);
    this.props.scope.dispose();
  }

  renderBody(){
    return (
      <div className="timepicker-dropdown-main">
        <ul>
          {
            this.state.dateList.map(item=>(
              <li
                key={item.value}
                onClick={this.selectItem.bind(this,item)}
                className={cn({
                  active:item.value===this.state.dateListSelectedValue
                })}>
                {item.text}
              </li>
            ),this)
          }
        </ul>
      </div>
    )
  }

  render() {
    return (
      <div ref="root" className="dropdown time-slider" style={this.props.style}>
        <strong onClick={this.toggleHandler.bind(this)}>
          <i className="iconfont icon-clock"></i>
          {this.state.text}
          <i className="iconfont icon-btn-arrow">&#xe619;</i>
        </strong>
        {this.state.isOpen?this.renderBody():null}
      </div>
    );
  }
}

export let SegmentDateScope = new SegmentDateStore();
SegmentDatePicker.defaultProps = {
  scope: SegmentDateScope,
  style: {}
}
